package com.lzx.adx.report.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.lzs.adx.commmon.service.impl.CrudServiceImpl;
import com.lzs.adx.commmon.utils.ConvertUtils;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.dao.ReportDao;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.entity.ReportEntity;
import com.lzx.adx.report.service.BackDataService;
import com.lzx.adx.report.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class ReportServiceImpl extends CrudServiceImpl<ReportDao, ReportEntity, ReportDTO> implements ReportService {

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    private BackDataService backDataService;

    @Override
    public QueryWrapper<ReportEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");
        String bizRequestId = (String)params.get("bizRequestId");
        String ordertime = (String)params.get("ordertime");
        String dspId = (String)params.get("dsp_id");

        QueryWrapper<ReportEntity> wrapper = new QueryWrapper<>();

        wrapper.eq(StringUtils.isNotBlank(id), "id", id);
        wrapper.eq(StringUtils.isNotBlank(dspId), "dsp_id", dspId);
        wrapper.eq(StringUtils.isNotBlank(bizRequestId), "biz_request_id", bizRequestId);
        wrapper.eq(StringUtils.isNotBlank(ordertime), "day_time", ordertime);
        wrapper.isNull(null != params.get("resultType"), "result_type");
        wrapper.last(null != params.get("limit"), "limit 1");
        return wrapper;
    }

    @Override
    public List<ReportDTO> list(Map<String, Object> params) {
        List<ReportDTO> list = super.list(params);
        if(CollectionUtil.isEmpty(list)){
            if(params.containsKey("bizRequestId")) {
                String bizRequestId = params.get("bizRequestId").toString();
                Query query = new Query(Criteria.where("bizRequestId").is(bizRequestId));
                List<ReportDTO> reportDTOS = mongoTemplate.find(query, ReportDTO.class);
                if(CollectionUtil.isNotEmpty(reportDTOS)){
                    //数据库查询不到去mongodb里面查询
                    log.info("命中mongodb的查询----请求ID{}",bizRequestId);
                    return reportDTOS;
                }
            }
        }
        return list;
    }

    @Override
    public void saveData(ReportDTO dto) {
        ReportEntity report=  reportMapper.toReport(dto);
        report.setDay(DateUtil.format(new Date(),createFormatter("yyyy-MM-dd")));
        report.setDayTime(DateUtil.format(new Date(),createFormatter("yyyyMMddHH")));


        this.baseDao.insert(report);
        dto.setId(report.getId());

        //存储一份到mongodb
        mongoTemplate.save(dto);

    }

    @Override
    public ReportDTO getNewData(String id, String orderTime) {
        LambdaQueryWrapper<ReportEntity> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ReportEntity::getDspId,id);
        lambdaQueryWrapper.eq(ReportEntity::getDayTime,orderTime);

        lambdaQueryWrapper.orderByDesc(ReportEntity::getDayTime);
        lambdaQueryWrapper.last("limit "+200);

        List<ReportEntity> reportEntities = this.baseDao.selectList(lambdaQueryWrapper);
        if(CollectionUtil.isNotEmpty(reportEntities)) {
            List<ReportEntity> collect = reportEntities.stream().filter(t -> StringUtils.isBlank(t.getResultType())).collect(Collectors.toList());
            if(CollectionUtil.isNotEmpty(collect)){
                ReportEntity reportEntity = collect.get(0);
                ReportDTO reportDTO = new ReportDTO();
                BeanUtils.copyProperties(reportEntity, reportDTO);
                return reportDTO;
            }
        }
        return  null;
    }

    @Override
    public void updateData(ReportDTO reportDTO,String eventType) {
        super.update(reportDTO);

        //1.存储回传数据

        backDataService.saveData(reportDTO,eventType);

        //更新mongodb内容
//        mongoTemplate.save(reportDTO);
    }

    public static DateTimeFormatter createFormatter(String pattern) {
        return DateTimeFormatter.ofPattern(pattern, Locale.getDefault())
                .withZone(ZoneId.systemDefault());
    }



}